package com.tiancheng.trade.order.feign;

import com.tiancheng.trade.commom.web.http.PlatformRequest;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.OrderQueryParamDTO;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.RefundCreateDTO;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.RefundQueryParamDTO;
import com.tiancheng.trade.order.feign.dto.orderSubSystem.RefundSubmitDTO;
import com.tiancheng.trade.order.util.CommonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单系统php版，查询老数据
 *
 * @author kellen
 * @date 2024/5/30
 */
@Slf4j
@Component
public class OrderSubSystemService {

    @Resource
    private PlatformRequest platformRequest;
    @Value(value = "${system.orderSub.domain}")
    private String orderSubDomain;

    /**
     * 查询用户订单数据
     * @param queryParam
     * @return
     */
    public List<Map<String, Object>> findByUser(OrderQueryParamDTO queryParam) {
        log.info("调用老系统/app/api/order-service/get-list-by-conditions:{}", JsonUtil.toJsonString(queryParam));
        Map<String, String> params = JsonUtil.fromJson(JsonUtil.toJsonString(queryParam), Map.class);
        try {
            String url = orderSubDomain + "/app/api/order-service/get-list-by-conditions";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            List<Map<String, Object>> orders = (List<Map<String, Object>>) dataMap.get("list");
            return orders;
        } catch (Exception e) {
            log.error("查询php订单系统，订单数据失败:" + e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 查询用户退款数据
     * @param queryParam
     * @return
     */
    public List<Map<String, Object>> findRefundByUser(RefundQueryParamDTO queryParam) {
        log.info("调用老系统/app/api/refund-service/get-list-by-conditions:{}", JsonUtil.toJsonString(queryParam));
        Map<String, String> params = JsonUtil.fromJson(JsonUtil.toJsonString(queryParam), Map.class);
        try {
            String url = orderSubDomain + "/app/api/refund-service/get-list-by-conditions";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            List<Map<String, Object>> orders = (List<Map<String, Object>>) dataMap.get("list");
            return orders;
        } catch (Exception e) {
            log.error("查询php订单系统，退款数据失败:" + e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    /**
     * 初始化收银台
     *
     * @param appType
     * @param version
     * @param orderId
     * @return
     */
    public Map<String, Object> initCashier(String orderId, String appType, String version) {
        log.info("调用老系统/app/api/order-service/init-cashier:{}", orderId);

        Map<String, String> params = new HashMap<>();
        params.put("order_id", orderId);

        Header[] headers = new Header[] {new BasicHeader("apptype", appType), new BasicHeader("appversion", version)};

        try {
            String url = orderSubDomain + "/app/api/order-service/init-cashier";
            Result result = platformRequest.formUrlencodedPostRequest(url, params, true, headers);
            log.info("调用老系统/app/api/order-service/init-order-cashier返回:{}", result);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            return (Map<String, Object>) resultMap.get("data");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取支付信息
     *
     * @param orderId
     * @param isFusion
     * @param channelCode
     * @param appType
     * @param version
     * @return
     */
    public Map<String, Object> getPayInfo(String orderId, int isFusion, String channelCode, String appType, String version) {
        log.info("调用老系统/app/api/order-service/get-order-pay-info:{}, {}, {}", orderId, isFusion, channelCode);

        Map<String, String> params = new HashMap<>();
        params.put("order_id", orderId);
        params.put("is_fusion", String.valueOf(isFusion));
        params.put("channel_code", channelCode);

        Header[] headers = new Header[] {new BasicHeader("apptype", appType), new BasicHeader("appversion", version)};

        try {
            String url = orderSubDomain + "/app/api/order-service/get-order-pay-info";
            Result result = platformRequest.formUrlencodedPostRequest(url, params, true, headers);
            log.info("调用老系统/app/api/order-service/get-order-pay-info返回:{}", result);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            return (Map<String, Object>) resultMap.get("data");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取订单支付状态
     * @param orderId
     * @return
     */
    public Map<String, Object> getPayStatus(String orderId) {
        log.info("调用老系统/app/api/order-service/get-order-pay-status:{}", orderId);

        Map<String, String> params = new HashMap<>();
        params.put("order_id", orderId);

        try {
            String url = orderSubDomain + "/app/api/order-service/get-order-pay-status";
            Result result = platformRequest.formUrlencodedPostRequest(url, params, true, null);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            return (Map<String, Object>) resultMap.get("data");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 查询订单信息
     * @param orderId
     * @return
     */
    public Map<String, Object> getOrderInfo(String orderId) {
        log.info("调用老系统查询订单/app/api/order-service/get-order-info:{}", orderId);

        Map<String, String> params = new HashMap<>();
        params.put("order_id", orderId);
        params.put("rand", CommonUtil.uuid());

        try {
            String url = orderSubDomain + "/app/api/order-service/get-order-info";
            Result result = platformRequest.formUrlencodedPostRequest(url, params, true, null);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            return (Map<String, Object>) resultMap.get("data");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 创建退款
     * @param refundCreateDTO
     * @return
     */
    public Map<String, Object> createRefund(RefundCreateDTO refundCreateDTO) {
        log.info("调用老系统创建退款/app/api/refund-service/submit-sub-order:{}", JsonUtil.toJsonString(refundCreateDTO));

        Map<String, String> params = JsonUtil.fromJson(JsonUtil.toJsonString(refundCreateDTO), Map.class);
        params.put("app_id", platformRequest.getServiceConfig().getClientId());

        try {
            String url = orderSubDomain + "/app/api/refund-service/submit-sub-order";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            return (Map<String, Object>) resultMap.get("data");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 提交退款
     * @param refundSubmitDTO
     * @return
     */
    public boolean submitRefund(RefundSubmitDTO refundSubmitDTO) {
        log.info("调用老系统提交退款/app/api/refund-service/execute:{}", JsonUtil.toJsonString(refundSubmitDTO));

        Map<String, String> params = JsonUtil.fromJson(JsonUtil.toJsonString(refundSubmitDTO), Map.class);

        try {
            String url = orderSubDomain + "/app/api/refund-service/execute";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            log.info("调用老系统提交退款/app/api/refund-service/execute返回:{}", result);

            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            if (dataMap.containsKey("status") && "refund_fail".equals(String.valueOf(dataMap.get("status")))) {
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 核销
     * @param orderId
     * @param subOrderId
     * @return
     */
    public boolean verification(String orderId, String subOrderId) {
        log.info("调用老系统核销/app/api/order-service/sub-order-charge:{},{}", orderId, subOrderId);

        Map<String, String> params = new HashMap<>();
        params.put("order_id", orderId);
        params.put("sub_order_id", subOrderId);

        try {
            String url = orderSubDomain + "/app/api/order-service/sub-order-charge";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 修改退款状态
     * @param refundId
     * @param status
     * @param description
     * @return
     */
    public boolean updateRefundStatus(String refundId, String status, String description) {
        log.info("调用老系统修改退款状态/app/api/refund-service/update-status:{},{}", refundId, status);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("refund_id", refundId);
        params.put("status", status);
        params.put("description", description);

        try {
            String url = orderSubDomain + "/app/api/refund-service/update-status";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 修改订单状态
     * @param orderId
     * @param orderStatus
     * @param operator
     * @param desc
     * @return
     */
    public boolean updateOrderStatus(String orderId, String orderStatus, String operator, String desc) {
        log.info("调用老系统修改订单状态/app/api/order-service/change-order-status:{},{}", orderId, orderStatus);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("rand", CommonUtil.uuid());
        params.put("order_id", orderId);
        params.put("order_status", orderStatus);
        params.put("operator", operator);
        params.put("update_desc", desc);

        try {
            String url = orderSubDomain + "/app/api/order-service/change-order-status";
            Result result = platformRequest.jsonPostRequest(url, params, true, null);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 根据订单中心订单号获取预授权订单orderStr
     * @param orderId 订单ID
     * @return
     */
    public Result getOrderStr(String orderId) {
        log.info("调用老系统根据订单中心订单号获取预授权订单orderStr /app/api/zhima-app/get-order-str orderId:{}", orderId);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("order_id", orderId);

        try {
            String url = orderSubDomain + "/app/api/zhima-app/get-order-str";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }


    /**
     * 查询已创建的预授权订单信息
     * @param alipayAuthNo 支付宝预授权单号
     * @return
     */
    public Result queryCreditOrder(String alipayAuthNo) {
        log.info("查询已创建的预授权订单信息 /app/api/zhima-app/query-credit-order alipay_auth_no:{}", alipayAuthNo);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("alipay_auth_no", alipayAuthNo);

        try {
            String url = orderSubDomain + "/app/api/zhima-app/query-credit-order";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 完结预授权订单
     * @param alipayAuthNo 支付宝预授权单号
     * @param payAmount 需要预授权转支付的金额
     * @param bizComplete 是否履约 0 否 1 是
     * @param description 完结说明
     * @return
     */
    public Result finishCreditOrder(String alipayAuthNo,Integer payAmount,Integer bizComplete,String description) {
        log.info("完结预授权订单 /app/api/zhima-service/finish-credit-order {} {} {}", alipayAuthNo,payAmount,bizComplete);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("alipay_auth_no", alipayAuthNo);
        params.put("pay_amount", payAmount);
        params.put("biz_complete", bizComplete);
        params.put("description", description);

        try {
            String url = orderSubDomain + "/app/api/zhima-service/finish-credit-order";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 取消预授权订单
     * @param alipayAuthNo 支付宝预授权单号
     * @param remark 备注
     * @return
     */
    public Result cancelCreditOrder(String alipayAuthNo,String remark) {
        log.info("取消预授权订单 /app/api/zhima-service/cancel-credit-order {}", alipayAuthNo);

        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("alipay_auth_no", alipayAuthNo);
        params.put("remark", remark);
        try {
            String url = orderSubDomain + "/app/api/zhima-service/cancel-credit-order";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }


    /**
     * 主动查询预授权回调状态
     * @param orderId 订单ID
     * @return
     */
    public Result queryConfirmStatus(String orderId) {
        log.info("主动查询预授权回调状态 /app/api/zhima-service/query-confirm-status {}", orderId);
        Map<String, Object> params = initQueryOldOrderSysParamsMap();
        params.put("order_id", orderId);
        try {
            String url = orderSubDomain + "/app/api/zhima-service/query-confirm-status";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

    private Map<String,Object> initQueryOldOrderSysParamsMap(){
        Map<String, Object> params = new HashMap<>();
        params.put("compatible","N");
        return params;
    }

    /**
     * 同步信用订单状态到老订单系统
     * @param params
     * @return
     */
    public Result updateCreditOrderState(Map<String, Object> params) {
        log.info("主动查询预授权回调状态 /app/api/zhima-service/query-confirm-status {}", params);
        try {
            String url = orderSubDomain + "/app/api/zhima-service/query-confirm-status";
            return platformRequest.jsonPostRequest(url, params, true, null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
}
